/**
 * Copyright (c) 广州小橘灯信息科技有限公司 2016-2017, wjun_java@163.com.
 * <p>
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl-3.0.txt
 * http://www.xjd2020.com
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jeegot.mall.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeegot.common.constants.JeegotConstants;
import com.jeegot.core.permission.AdminMenu;
import com.jeegot.core.response.Response;
import com.jeegot.mall.entity.*;
import com.jeegot.mall.service.*;
import com.jeegot.web.controller.admin.AdminBaseController;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author： wjun_java@163.com
 * @date： 2021/6/10
 * @description：
 * @modifiedBy：
 * @version: 1.0
 */
@Controller
@AdminMenu(name = "商品", icon = "<i class=\"nav-icon fa fa-fw fa-tags\"></i>", sort = 1)
@RequestMapping(JeegotConstants.ADMIN_MAPPING + "/product")
public class ProductController extends AdminBaseController {

	@Autowired
	private IProductService productService;

	@Autowired
	private IProductCategoryService productCategoryService;

	@Autowired
	private IProductCommentService productCommentService;

	@Autowired
	private IProductImageService productImageService;

	@Autowired
	private IProductSkuItemService productSkuItemService;

	@Autowired
	private IProductSpecService productSpecService;

	@Autowired
	private IProductSpecValueService productSpecValueService;

	@Autowired
	private IPostageTemplateService postageTemplateService;

	@Autowired
	private IPostageTemplateSetService postageTemplateSetService;

	@RequestMapping("list")
	@RequiresPermissions("product:list")
	@AdminMenu(name = "商品管理", sort = 1)
	public String list(@RequestParam(name = "page", required = false, defaultValue = "1") Long page,
					   @RequestParam(name = "pageSize", required = false, defaultValue = "10") Long pageSize,
					   @RequestParam(name = "title", required = false) String title,
					   @RequestParam(name = "status", required = false, defaultValue = "publish") String status,
					   @RequestParam(name = "categoryId", required = false) String categoryId,
					   Model model) {

		QueryWrapper queryWrapper = new QueryWrapper();
		if(StringUtils.isNotBlank(title)) {
			queryWrapper.like("a.title", title);
		}
		if(StringUtils.isNotBlank(categoryId)) {
			queryWrapper.eq("acr.category_id", categoryId);
		}
		queryWrapper.eq("a.status", status);
		queryWrapper.orderByDesc("a.created");
		Page pageParam = new Page<>(page, pageSize);
		Page<IProductService.ProductVo> pageData = productService.pageProduct(pageParam, queryWrapper);
		model.addAttribute(PAGE_DATA_ATTR, pageData);

		model.addAttribute("categoryList", productCategoryService.getCategoryList(getLoginUser().getId()));

		return "/admin/product/list";
	}

	@AdminMenu(name = "新建", sort = 2)
	@RequestMapping("edit")
	public String edit(@RequestParam(name = "id", required = false) Long id, Model model) {
		model.addAttribute("product", productService.getById(id));
		model.addAttribute("categories", productCategoryService.getProductCategoryListByProductId(id));
		model.addAttribute("categoryList", productCategoryService.getCategoryList(getLoginUser().getId()));
		model.addAttribute("tags", productCategoryService.getProductTagListByProductId(id));
		model.addAttribute("tagList", productCategoryService.getTagList(getLoginUser().getId()));
		model.addAttribute("images", productImageService.getProductImageList(id));
		model.addAttribute("postageTemplates", postageTemplateService.getUserPostageTemplate(getLoginUser().getId()));
		model.addAttribute("specs", productSpecService.getUserProductSpecList(getLoginUser().getId()));
		List<ProductSkuItem> productSkuItemList = productSkuItemService.getProductSkuItemList(id);
		model.addAttribute("productSkuList", productSkuItemList);
		if(productSkuItemList != null && productSkuItemList.size()>0){
			Set<String> skuItemSet = new HashSet<>();
			for(ProductSkuItem productSkuItem : productSkuItemList){
				String[] skuNames = productSkuItem.getSkuName().split(" ");
				for(String skuName : skuNames){
					skuItemSet.add(skuName);
				}
			}
			StringBuffer stringBuffer = new StringBuffer();
			skuItemSet.forEach(item -> stringBuffer.append(item).append(","));
			model.addAttribute("skuItems", stringBuffer.toString());
		}
		return "admin/product/edit";
	}

	@PostMapping("doSave")
	public ResponseEntity doSave(@Validated Product product) {
		try {
			productService.saveProduct(product);
			return Response.success();
		} catch (Exception e) {
			return Response.fail(e.getMessage());
		}
	}

	@AdminMenu(name = "分类", sort = 3)
	@RequestMapping("category/list")
	public String categoryList(@RequestParam(name = "page", required = false, defaultValue = "1") Long page,
							   @RequestParam(name = "pageSize", required = false, defaultValue = "10") Long pageSize,
							   Model model) {
		QueryWrapper queryWrapper = new QueryWrapper();
		Page pageParam = new Page<>(page, pageSize);
		Page<IProductCategoryService.ProductCategoryVo> pageData = productCategoryService.pageProductCategory(pageParam, queryWrapper);
		model.addAttribute(PAGE_DATA_ATTR, pageData);
		return "admin/product/category_list";
	}

	@RequestMapping("category/edit")
	public String editCategory(@RequestParam(name = "id", required = false) Long id, Model model) {
		model.addAttribute("productCategory", productCategoryService.getById(id));
		model.addAttribute("productCategoryList", productCategoryService.list());
		return "admin/product/category_edit";
	}

	@PostMapping("category/doSave")
	public ResponseEntity doSaveCategory(ProductCategory productCategory) {
		productCategoryService.saveOrUpdate(productCategory);
		return Response.success();
	}

	@PostMapping("category/doDelete")
	public ResponseEntity doDeleteCategory(@RequestParam(name = "id") Long id) {
		productCategoryService.deleteByCategoryId(id);
		return Response.success();
	}

	@AdminMenu(name = "规格", sort = 4)
	@RequestMapping("spec/list")
	public String specList(@RequestParam(name = "page", required = false, defaultValue = "1") Long page,
							  @RequestParam(name = "pageSize", required = false, defaultValue = "10") Long pageSize,
							  Model model) {
		QueryWrapper queryWrapper = new QueryWrapper();
		Page pageParam = new Page<>(page, pageSize);
		Page<ProductSpec> pageData = productSpecService.page(pageParam, queryWrapper);
		model.addAttribute(PAGE_DATA_ATTR, pageData);
		return "admin/product/spec_list";
	}

	@RequestMapping("spec/edit")
	public String editSpec(@RequestParam(name = "id", required = false) Long id, Model model) {
		model.addAttribute("spec", productSpecService.getById(id));
		model.addAttribute("specValueList", productSpecValueService.getSpecValueList(id));
		return "admin/product/spec_edit";
	}

	@PostMapping("spec/doSave")
	public ResponseEntity doSaveSpec(@Validated ProductSpec productSpec) {
		try {
			productSpecService.saveProductSpec(productSpec);
			return Response.success();
		} catch (Exception e) {
			return Response.fail(e.getMessage());
		}
	}

	@PostMapping("spec/doDelete")
	public ResponseEntity doDeleteSpec(@RequestParam(name = "id") Long id) {
		productSpecService.removeById(id);
		return Response.success();
	}

	@AdminMenu(name = "运费", sort = 5)
	@RequestMapping("postage/list")
	public String postageList(@RequestParam(name = "page", required = false, defaultValue = "1") Long page,
						   @RequestParam(name = "pageSize", required = false, defaultValue = "10") Long pageSize,
						   Model model) {
		QueryWrapper queryWrapper = new QueryWrapper();
		Page pageParam = new Page<>(page, pageSize);
		Page<PostageTemplate> pageData = postageTemplateService.page(pageParam, queryWrapper);
		model.addAttribute(PAGE_DATA_ATTR, pageData);
		return "admin/product/postage_list";
	}

	@RequestMapping("postage/edit")
	public String editPostage(@RequestParam(name = "id", required = false) Long id, Model model) {
		model.addAttribute("postage", postageTemplateService.getById(id));

		List<PostageTemplateSet> freightTemplateSetList = postageTemplateSetService.getTemplateSetList(id);
		List<PostageTemplateSet> customFreightTemplateList = new ArrayList<>();
		freightTemplateSetList.forEach(item ->{
			if(item.getAreaContent().equals("default")){
				model.addAttribute("defaultTemplate", item);
			}else{
				customFreightTemplateList.add(item);
			}
		});
		model.addAttribute("templateSetList", customFreightTemplateList);

		return "admin/product/postage_edit";
	}

	@PostMapping("postage/doSave")
	public ResponseEntity doSavePostage(@Validated PostageTemplate postageTemplate) {
		try {
			postageTemplateService.savePostageTemplate(postageTemplate);
			return Response.success();
		} catch (Exception e) {
			return Response.fail(e.getMessage());
		}
	}

	@PostMapping("postage/doDelete")
	public ResponseEntity doDeletePostage(@RequestParam(name = "id") Long id) {
		postageTemplateService.removeById(id);
		return Response.success();
	}

	@AdminMenu(name = "评论", sort = 6)
	@RequestMapping("comment/list")
	public String commentList(@RequestParam(name = "page", required = false, defaultValue = "1") Long page,
							  @RequestParam(name = "pageSize", required = false, defaultValue = "10") Long pageSize,
							  Model model) {
		QueryWrapper queryWrapper = new QueryWrapper();
		Page pageParam = new Page<>(page, pageSize);
		Page<IProductCommentService.ProductCommentVo> pageData = productCommentService.pageProductComment(pageParam, queryWrapper);
		model.addAttribute(PAGE_DATA_ATTR, pageData);
		return "admin/product/comment_list";
	}

	@RequestMapping("comment/edit")
	public String editComment(@RequestParam(name = "id", required = false) Long id, Model model) {
		model.addAttribute("productComment", productCommentService.getById(id));
		return "admin/product/comment_edit";
	}

	@PostMapping("comment/doSave")
	public ResponseEntity doSaveComment(@Validated ProductComment productComment) {
		productCommentService.saveOrUpdate(productComment);
		return Response.success();
	}

	@PostMapping("comment/doDelete")
	public ResponseEntity doDeleteComment(@RequestParam(name = "id") Long id) {
		productCommentService.removeById(id);
		return Response.success();
	}

}
